package com.bangdream.michelia.tool;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;


import java.util.ArrayList;

/**
 * @date on 2018/6/19 21:46
 * @email 909732184@qq.com
 */
public abstract class MyLoopVPAdapter<T> extends FragmentPagerAdapter implements ViewPager.OnPageChangeListener{

    //    当前页面
    private int currentPosition = 0;

    protected ArrayList<Fragment> views;
    protected ViewPager mViewPager;
    private OnViewPageSelected onViewPageSelected;

    public OnViewPageSelected getOnViewPageSelected() {
        return onViewPageSelected;
    }

    public void setOnViewPageSelected(OnViewPageSelected onViewPageSelected) {
        this.onViewPageSelected = onViewPageSelected;
    }
    //抛出去给其他类实现其他逻辑
    public interface OnViewPageSelected{
        void onMyPageSelected(int position);

    }
    public MyLoopVPAdapter(FragmentManager fm, ArrayList<T> datas, ViewPager viewPager) {
        super(fm);
        views = new ArrayList<>();
//        如果数据大于一条
        if(datas.size() > 1) {
//            添加最后一页到第一页
            datas.add(0,datas.get(datas.size()-1));
//            添加第一页(经过上行的添加已经是第二页了)到最后一页
            datas.add(datas.get(1));
        }
        for (int i = 0;i<datas.size();i++) {
            views.add(getItem(i));
        }
        mViewPager = viewPager;
        viewPager.setAdapter(this);
        viewPager.addOnPageChangeListener(this);
        viewPager.setCurrentItem(1,false);
    }

    public abstract Fragment getItem(int position);

    @Override
    public int getCount() {
        return views.size();
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {
        currentPosition = position;
        if(onViewPageSelected!=null){
            int index = position-1;
            //因为在数据的头部和尾部都加了一条数据实现循环滑动  所以 如果是滑动到第一条和最后一条 不计入改变事件
            if (currentPosition == 0||currentPosition==views.size()-1) {
                return;
            }
            onViewPageSelected.onMyPageSelected(index);
        }
    }

    @Override
    public void onPageScrollStateChanged(int state) {
//        若viewpager滑动未停止，直接返回
        if (state != ViewPager.SCROLL_STATE_IDLE) return;
//        若当前为第一张，设置页面为倒数第二张
        if (currentPosition == 0) {
            mViewPager.setCurrentItem(views.size()-2,false);
        } else if (currentPosition == views.size()-1) {
//        若当前为倒数第一张，设置页面为第二张
            mViewPager.setCurrentItem(1,false);
        }
    }
}
